import { storeToRefs } from "pinia"
import axiosAPI from ".."
import appStore from "@/stores"

var errorMsg = ""
const { token } = storeToRefs(appStore.userStore)
const { switchTipStatus } = appStore.homeviewStore

export async function GetUserInfo(callback, errorback) {
  axiosAPI("get", "/api/userinfo/")
    .then((rData) => {
      callback(rData)
    })
    .catch((error) => {
      switchTipStatus({ level: "warning", msg: error.response.data.error })
      //   errorback(error)
    })
}

export async function UpdateUserView(callback, errorback) {
  axiosAPI("get", "/api/userviews/")
    .then(() => {
      callback()
    })
    .catch(() => {
      switchTipStatus({ level: "warning", msg: "网络错误, 请重试!" })
      //   errorback(error)
    })
}

/**
 * 用户登录
 * @param {Object} data - 登录数据
 * @param {function} callback - 成功回调，参数为响应数据
 * @param {function} errorback - 失败回调
 * @returns {void}
 */
export async function Login(data, callback, errorback) {
  axiosAPI("post", "/api/login/", {}, {}, data)
    .then((rData) => {
      callback(rData)
    })
    .catch((error) => {
      if (error.status === 401 || error.status === 400) {
        switchTipStatus({ level: "warning", msg: error.response.data.error })
      } else {
        switchTipStatus({ level: "warning", msg: "网络错误, 请重试！" })
      }
    })
}

/**
 * 获取音乐列表
 * @param {function} callback - 成功回调，参数为音乐数据
 * @param {function} errorback - 失败回调
 * @returns {void}
 */
export async function GetMusicsView(callback, errorback) {
  axiosAPI("get", "/api/musics/")
    .then((rData) => {
      callback(rData["songs"])
    })
    .catch((error) => {
      switchTipStatus({ level: "warning", msg: "获取音乐资列表失败！请重试！" })
      //   errorback(error)
    })
}

/**
 * 获取下载链接
 * @param {Object} data - 请求数据
 * @param {function} callback - 成功回调，参数为 url
 * @param {function} errorback - 失败回调
 * @returns {void}
 */
export async function GetUrl(data, callback, errorback) {
  axiosAPI(
    "post",
    "/api/url/",
    {
      Authorization: `Bearer ${token.value}`,
      "Content-Type": "application/json",
    },
    {},
    data
  )
    .then((rData) => {
      callback(rData.url)
    })
    .catch((error) => {
      if (error.status === 401) {
        errorMsg = "无权限，请先登录"
      } else {
        errorMsg = "下载失败，请重试！"
      }
      switchTipStatus({ level: "warning", msg: errorMsg })
      //   errorback(error)
    })
}
